﻿// CrackDialog.cpp: 实现文件
//

#include "pch.h"
#include "LiftTheRestrictions.h"
#include "afxdialogex.h"
#include "CrackDialog.h"
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <time.h>
#include <nlohmann/json.hpp>
#include "WininetHttp.h"



// CrackDialog 对话框

IMPLEMENT_DYNAMIC(CrackDialog, CDialogEx)


using json = nlohmann::json; // 简化命名空间

CrackDialog::CrackDialog(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_DIALOG_CRACK, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

CrackDialog::~CrackDialog()
{
}

void CrackDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}


BEGIN_MESSAGE_MAP(CrackDialog, CDialogEx)
END_MESSAGE_MAP()

int Pnum = 0, Cnum;//父窗口数量，每一级父窗口的子窗口数量  

CStringA GetWindowClassName(HWND hWnd)
{
	CStringA className;
	::GetClassNameA(hWnd, className.GetBufferSetLength(MAX_PATH + 1), MAX_PATH);
	className.ReleaseBuffer();
	return className;
}

bool ModifyMemory(DWORD processId, LPVOID address) {
	HANDLE hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, processId);
	if (hProcess == NULL) {
		DWORD err = GetLastError();
		// 处理权限问题（可能需要以管理员身份运行）
		return false;
	}

	BYTE buffer = 0;
	SIZE_T bytesRead = 0;
	// 读取内存
	if (!ReadProcessMemory(hProcess, address, &buffer, sizeof(buffer), &bytesRead)) {
		CloseHandle(hProcess);
		return false;
	}

	if (bytesRead != sizeof(buffer)) {
		CloseHandle(hProcess);
		return false; // 未完整读取
	}

	// 检查是否为0x74
	if (buffer == 0x74) {
		BYTE newValue = 0xEB;
		// 修改内存保护属性（如果需要）
		DWORD oldProtect;
		if (!VirtualProtectEx(hProcess, address, sizeof(newValue), PAGE_EXECUTE_READWRITE, &oldProtect)) {
			CloseHandle(hProcess);
			return false;
		}

		// 写入新值
		SIZE_T bytesWritten = 0;
		if (!WriteProcessMemory(hProcess, address, &newValue, sizeof(newValue), &bytesWritten)) {
			VirtualProtectEx(hProcess, address, sizeof(newValue), oldProtect, &oldProtect); // 恢复保护
			CloseHandle(hProcess);
			return false;
		}

		// 恢复原始保护属性（可选）
		//VirtualProtectEx(hProcess, address, sizeof(newValue), oldProtect, &oldProtect);
	}

	CloseHandle(hProcess);
	return true;
}



BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
	if (GetParent(hWnd) == NULL)
	{
		//&& IsWindowVisible(hWnd)  //如果判断是否顶层窗口并且可见加上该条件  
		Pnum++;
		Cnum = 0;
		char WindowTitle[100] = { 0 };
		DWORD dwPID = NULL;
		GetWindowThreadProcessId(hWnd, &dwPID);


		::GetWindowTextA(hWnd, WindowTitle, 100);
		CStringA className = GetWindowClassName(hWnd);
		CStringA str;

		if (lParam == dwPID) {
			OutputDebugStringA("-------------------------------------------\n");
			str.Format("%d: %s  hwnd:%x  pid:%x \n", Pnum, WindowTitle, (int)hWnd, dwPID);
			OutputDebugStringA(str.GetString());

			LPVOID bloodAdress = (LPVOID)0x001DA33F;
			ModifyMemory(dwPID, bloodAdress);
		}
	}
	return true;
}

DWORD FindProcessId(LPCTSTR szProcessName) {
	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(PROCESSENTRY32);
	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (Process32First(hSnap, &pe32)) {
		do {
			if (_tcsicmp(pe32.szExeFile, szProcessName) == 0) {
				EnumWindows(EnumWindowsProc, pe32.th32ProcessID);
			}
		} while (Process32Next(hSnap, &pe32));
	}
	CloseHandle(hSnap);
	return 0;
}

UINT  getTime(LPVOID  lParam)
{
	CWininetHttp  req;
	string resultData = req.RequestJsonInfo("f.m.suning.com/api/ct.do");
	string resultDataDebug = resultData+ "\n";
	OutputDebugStringA(resultDataDebug.c_str());



	try {
		// 解析 JSON 字符串
		json j = json::parse(resultData);
		string api = j["api"].get<std::string>();
		api = api + "\n";

		// 提取 currentTime 字段的值（注意类型为 int64_t）
		time_t current_time = j["currentTime"].get<time_t>();

		//// 输出结果
		//std::cout << "Current Time: " << current_time << std::endl;

		char printShow[256];
		sprintf_s(printShow, "Current Time: %lld \n", current_time);
		OutputDebugStringA(printShow);
		OutputDebugStringA(api.c_str());

	}
	catch (const json::exception& e) {
		// 捕获 JSON 解析或字段访问的异常
		std::cerr << "JSON Error: " << e.what() << std::endl;

		resultDataDebug = "JSON Error: " ;
		OutputDebugStringA(resultDataDebug.c_str());
		return 1;
	}


	return 1;
}

// CrackDialog 消息处理程序


// CLiftTheRestrictionsDlg 消息处理程序

BOOL CrackDialog::OnInitDialog()
{
	CDialogEx::OnInitDialog();


	AfxBeginThread(getTime, (LPVOID)this);//启动新的线程 获取时间

	const TCHAR* szTargetProcess = _T("longhun_multifunctional.exe");

	// 获取进程ID
	DWORD dwPid = FindProcessId(szTargetProcess);
	//if (dwPid == 0) {
	//	AfxMessageBox(_T("进程未找到"));
	//}

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}


void CrackDialog::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CrackDialog::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}
